<template>
  <a-layout style="min-height: 100vh; background: #f5f7fa;">
    <nav-bar />
    
    <a-layout-content style="padding: 30px 50px; max-width: 1400px; margin: 0 auto; width: 100%;">
      <!-- 页面标题 -->
      <div style="text-align: center; margin-bottom: 24px;">
        <h1 style="font-size: 28px; color: #2c3e50; font-weight: 600;">
          🧪 {{ $t('structureSearch.pageTitle') }}
        </h1>
        <p style="color: #606266;">{{ $t('structureSearch.pageSubtitle') }}</p>
      </div>
      
      <!-- 输入区域 -->
      <a-card style="margin-bottom: 16px; border-radius: 8px; border: 1px solid #e4e7ed;">
        <a-form layout="vertical">
          <!-- 输入模式选择 -->
          <a-form-item :label="$t('structureSearch.inputModeLabel')">
            <a-radio-group v-model:value="inputMode" button-style="solid" size="large">
              <a-radio-button value="database">
                <database-outlined /> {{ $t('structureSearch.inputModeDatabase') }}
              </a-radio-button>
              <a-radio-button value="upload">
                <upload-outlined /> {{ $t('structureSearch.inputModeUpload') }}
              </a-radio-button>
            </a-radio-group>
          </a-form-item>
          
          <!-- 数据库选择模式 -->
          <a-form-item 
            v-if="inputMode === 'database'"
            :label="$t('structureSearch.selectProteinLabel')"
          >
            <a-select
              v-model:value="selectedAccession"
              show-search
              :placeholder="$t('structureSearch.selectProteinPlaceholder')"
              :filter-option="filterAccession"
              :loading="loadingProteins"
              size="large"
              style="width: 100%;"
            >
              <a-select-option 
                v-for="protein in proteinsWithPDB" 
                :key="protein.accession" 
                :value="protein.accession"
              >
                <div style="display: flex; justify-content: space-between;">
                  <span><strong>{{ protein.accession }}</strong></span>
                  <span style="color: #909399; font-size: 12px;">{{ protein.species }}</span>
                </div>
              </a-select-option>
            </a-select>
          </a-form-item>
          
          <!-- 文件上传模式 -->
          <a-form-item 
            v-if="inputMode === 'upload'"
            :label="$t('structureSearch.uploadFileLabel')"
          >
            <a-upload-dragger
              v-model:file-list="fileList"
              :before-upload="beforeUpload"
              :max-count="1"
              accept=".pdb"
              @remove="handleRemove"
            >
              <p class="ant-upload-drag-icon">
                <file-outlined style="color: #409eff; font-size: 48px;" />
              </p>
              <p class="ant-upload-text">{{ $t('structureSearch.uploadFileHint') }}</p>
              <p class="ant-upload-hint">{{ $t('structureSearch.uploadFileSupport') }}</p>
            </a-upload-dragger>
          </a-form-item>
          
          <!-- 搜索参数 -->
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item 
                :label="$t('structureSearch.tmScoreLabel')" 
                :help="$t('structureSearch.tmScoreHelp')"
              >
                <a-input-number
                  v-model:value="tmScoreThreshold"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  style="width: 100%;"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item 
                :label="$t('structureSearch.maxResultsLabel')" 
                :help="$t('structureSearch.maxResultsHelp')"
              >
                <a-input-number
                  v-model:value="maxResults"
                  :min="10"
                  :max="500"
                  :step="10"
                  style="width: 100%;"
                />
              </a-form-item>
            </a-col>
          </a-row>
          
          <!-- 操作按钮 -->
          <a-form-item>
            <a-space>
              <a-button 
                type="primary" 
                size="large" 
                @click="searchStructure" 
                :loading="searching"
                :disabled="!canSearch"
              >
                <template #icon><search-outlined /></template>
                {{ $t('structureSearch.searchButton') }}
              </a-button>
              <a-button size="large" @click="clearForm">
                {{ $t('structureSearch.clearButton') }}
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
      
      <!-- 搜索结果 -->
      <a-card 
        v-if="searchResults" 
        style="border-radius: 8px; border: 1px solid #e4e7ed;"
      >
        <template #title>
          <span style="font-size: 18px; color: #2c3e50; font-weight: 600;">
            {{ $t('structureSearch.resultsTitle') }}
            <a-tag v-if="searchResults.cached" color="blue" style="margin-left: 8px;">
              <template #icon><thunderbolt-outlined /></template>
              {{ $t('structureSearch.cached') }}
            </a-tag>
          </span>
        </template>
        
        <!-- 统计信息 -->
        <a-row :gutter="16" style="margin-bottom: 16px;">
          <a-col :span="6">
            <a-statistic 
              :title="$t('structureSearch.queryIdentifier')" 
              :value="searchResults.query_identifier"
            >
              <template #prefix>
                <experiment-outlined style="color: #1890ff;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              :title="$t('structureSearch.totalHits')" 
              :value="searchResults.total_hits"
            >
              <template #prefix>
                <check-circle-outlined style="color: #52c41a;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              v-if="searchResults.execution_time"
              :title="$t('structureSearch.executionTime')" 
              :value="searchResults.execution_time.toFixed(3)" 
              suffix="s"
            >
              <template #prefix>
                <clock-circle-outlined style="color: #faad14;" />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic 
              :title="$t('structureSearch.cacheStatus')" 
              :value="searchResults.cached ? $t('structureSearch.cacheHit') : $t('structureSearch.cacheMiss')"
            >
              <template #prefix>
                <database-outlined :style="{ color: searchResults.cached ? '#52c41a' : '#d9d9d9' }" />
              </template>
            </a-statistic>
          </a-col>
        </a-row>
        
        <!-- 结果表格 -->
        <a-table
          :dataSource="searchResults.results"
          :columns="columns"
          :pagination="{ pageSize: 20, showSizeChanger: true, showQuickJumper: true }"
          rowKey="accession"
          :scroll="{ x: 1200 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'accession'">
              <router-link :to="`/protein/${record.id}`">
                <a-typography-text copyable style="color: #1890ff;">
                  {{ record.accession }}
                </a-typography-text>
              </router-link>
            </template>
            
            <template v-else-if="column.key === 'species'">
              <a-tooltip :title="record.species">
                <span style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; display: block;">
                  {{ record.species }}
                </span>
              </a-tooltip>
            </template>
            
            <template v-else-if="column.key === 'tm_score'">
              <a-progress
                :percent="record.tm_score * 100"
                :format="percent => `${(percent / 100).toFixed(3)}`"
                :strokeColor="getTMScoreColor(record.tm_score)"
                :showInfo="true"
                style="width: 150px;"
              />
            </template>
            
            <template v-else-if="column.key === 'probability'">
              <span :style="{ 
                color: record.probability > 0.95 ? '#52c41a' : record.probability > 0.8 ? '#1890ff' : '#606266',
                fontFamily: 'monospace'
              }">
                {{ record.probability.toFixed(4) }}
              </span>
            </template>
            
            <template v-else-if="column.key === 'rmsd'">
              <span style="font-family: monospace;">
                {{ record.rmsd }} Å
              </span>
            </template>
            
            <template v-else-if="column.key === 'has_pdb'">
              <a-tag :color="record.has_pdb ? 'success' : 'default'">
                {{ record.has_pdb ? $t('structureSearch.table.hasStructure') : $t('structureSearch.table.noStructure') }}
              </a-tag>
            </template>
          </template>
        </a-table>
        
        <!-- 日志面板 -->
        <a-collapse v-if="searchResults.logs" style="margin-top: 16px;">
          <a-collapse-panel key="logs" :header="`📋 ${$t('structureSearch.viewLogs')}`">
            <div 
              v-for="(log, idx) in searchResults.logs" 
              :key="idx" 
              style="font-family: monospace; font-size: 12px; padding: 4px 0; line-height: 1.8;"
            >
              <span :style="{ color: log.level === 'error' ? '#f5222d' : '#606266' }">
                [{{ formatLogTime(log.timestamp) }}] {{ log.message }}
              </span>
            </div>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
    </a-layout-content>
  </a-layout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { 
  SearchOutlined, 
  DatabaseOutlined,
  UploadOutlined,
  ThunderboltOutlined,
  ExperimentOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  FileOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import config from '../config/env'
import NavBar from '../components/NavBar.vue'

const { t } = useI18n()

// 输入模式
const inputMode = ref('database')
const selectedAccession = ref(undefined)
const fileList = ref([])

// 搜索参数
const tmScoreThreshold = ref(0.5)
const maxResults = ref(100)

// 状态
const searching = ref(false)
const searchResults = ref(null)
const loadingProteins = ref(false)
const proteinsWithPDB = ref([])

// 是否可以搜索
const canSearch = computed(() => {
  if (inputMode.value === 'database') {
    return selectedAccession.value !== undefined
  } else {
    return fileList.value.length > 0
  }
})

// 表格列定义
const columns = computed(() => [
  { 
    title: t('structureSearch.table.accession'), 
    dataIndex: 'accession', 
    key: 'accession', 
    width: 150, 
    fixed: 'left' 
  },
  { 
    title: t('structureSearch.table.species'), 
    dataIndex: 'species', 
    key: 'species', 
    width: 200, 
    ellipsis: true 
  },
  { 
    title: t('structureSearch.table.type'), 
    dataIndex: 'type', 
    key: 'type', 
    width: 120 
  },
  { 
    title: t('structureSearch.table.tmScore'), 
    dataIndex: 'tm_score', 
    key: 'tm_score', 
    width: 180,
    sorter: (a, b) => a.tm_score - b.tm_score,
    defaultSortOrder: 'descend'
  },
  { 
    title: t('structureSearch.table.probability'), 
    dataIndex: 'probability', 
    key: 'probability', 
    width: 100,
    sorter: (a, b) => a.probability - b.probability
  },
  { 
    title: t('structureSearch.table.rmsd'), 
    dataIndex: 'rmsd', 
    key: 'rmsd', 
    width: 100,
    sorter: (a, b) => a.rmsd - b.rmsd
  },
  { 
    title: t('structureSearch.table.alignmentLength'), 
    dataIndex: 'alignment_length', 
    key: 'alignment_length', 
    width: 100 
  },
  { 
    title: t('structureSearch.table.targetLength'), 
    dataIndex: 'target_length', 
    key: 'target_length', 
    width: 100 
  },
  { 
    title: t('structureSearch.table.pdbStructure'), 
    dataIndex: 'has_pdb', 
    key: 'has_pdb', 
    width: 100, 
    align: 'center' 
  }
])

// 加载有PDB文件的蛋白质列表
const loadProteinsWithPDB = async () => {
  loadingProteins.value = true
  try {
    const response = await axios.get(`${config.API_BASE_URL}/api/autocomplete/`, {
      params: { q: '', limit: 1000 }
    })
    
    // 过滤出有PDB文件的蛋白质
    proteinsWithPDB.value = response.data
      .filter(p => p.has_pdb)
      .map(p => ({
        accession: p.value,
        species: p.label.split(' - ')[0] || p.value
      }))
  } catch (error) {
    console.error('Failed to load proteins:', error)
    message.error('加载蛋白质列表失败')
  } finally {
    loadingProteins.value = false
  }
}

// 过滤Accession
const filterAccession = (input, option) => {
  const accession = option.value.toLowerCase()
  const species = option.children[0].children[1].children.toLowerCase()
  return accession.includes(input.toLowerCase()) || species.includes(input.toLowerCase())
}

// 文件上传前验证
const beforeUpload = (file) => {
  const isPDB = file.name.endsWith('.pdb')
  if (!isPDB) {
    message.error(t('structureSearch.fileError'))
    return false
  }
  
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error(t('structureSearch.fileTooLarge'))
    return false
  }
  
  return false // 阻止自动上传
}

// 移除文件
const handleRemove = () => {
  fileList.value = []
}

// 执行搜索
const searchStructure = async () => {
  if (!canSearch.value) {
    message.error(t('structureSearch.noInput'))
    return
  }
  
  searching.value = true
  searchResults.value = null
  
  try {
    const formData = new FormData()
    
    if (inputMode.value === 'database') {
      formData.append('query_accession', selectedAccession.value)
    } else {
      formData.append('pdb_file', fileList.value[0].originFileObj)
    }
    
    formData.append('tm_score_threshold', tmScoreThreshold.value)
    formData.append('max_results', maxResults.value)
    
    const response = await axios.post(
      `${config.API_BASE_URL}/api/search/structure/`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    
    searchResults.value = response.data
    
    if (response.data.total_hits === 0) {
      message.warning(t('structureSearch.noResults'))
    } else {
      const cached = response.data.cached ? `(${t('structureSearch.cached')})` : ''
      const time = response.data.execution_time 
        ? ` - ${response.data.execution_time.toFixed(3)}s` 
        : ''
      message.success(t('structureSearch.searchSuccess', { count: response.data.total_hits }) + cached + time)
    }
  } catch (error) {
    const detail = error.response?.data?.detail || error.message
    message.error(t('structureSearch.searchFailed') + ': ' + detail)
    console.error('Search error:', error)
  } finally {
    searching.value = false
  }
}

// 清空表单
const clearForm = () => {
  selectedAccession.value = undefined
  fileList.value = []
  searchResults.value = null
  message.info(t('structureSearch.cleared'))
}

// TM-score颜色映射
const getTMScoreColor = (tmScore) => {
  if (tmScore >= 0.8) return '#52c41a'  // 绿色:高相似
  if (tmScore >= 0.6) return '#1890ff'  // 蓝色:中等相似
  if (tmScore >= 0.4) return '#faad14'  // 橙色:低相似
  return '#f5222d'  // 红色:很低相似
}

// 格式化日志时间
const formatLogTime = (timestamp) => {
  if (!timestamp) return ''
  const time = timestamp.split('T')[1]?.split('.')[0]
  return time || timestamp
}

// 挂载时加载蛋白质列表
onMounted(() => {
  loadProteinsWithPDB()
})
</script>

<style scoped>
:deep(.ant-btn-primary) {
  background: #409eff;
  border-color: #409eff;
}

:deep(.ant-btn-primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

:deep(.ant-radio-button-wrapper-checked) {
  background: #409eff !important;
  border-color: #409eff !important;
}

:deep(.ant-statistic-title) {
  color: #606266;
  font-size: 14px;
}

:deep(.ant-statistic-content) {
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  color: #2c3e50;
  font-weight: 600;
}

:deep(.ant-progress-text) {
  font-size: 12px;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #e4e7ed;
}

:deep(.ant-collapse) {
  background: #fafafa;
  border: 1px solid #e4e7ed;
}

:deep(.ant-collapse-header) {
  font-weight: 600;
  color: #2c3e50;
}

:deep(.ant-upload-drag) {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
}

:deep(.ant-upload-drag:hover) {
  border-color: #409eff;
}
</style>

